﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using Edge.Business.Domain.Application;
using Edge.Common.ComponentModel.Parameters;
using Edge.Common.Services;
using Shop.Business.Domain.Customers;
using Shop.Business.Domain.Orders;
using Shop.Business.Domain.Orders.Logic;
using Shop.Web.AppCode;

namespace Shop.Web.AjaxPages
{
    public partial class OrderProductList : ShopBasePage
    {
        [QueryParameter("preorder", IsRequired = false)]
        public bool preorder = false;

        protected void Page_Load(object sender, EventArgs e)
        {
            WebParameterAttribute.SetValues(this, Request);
            Order SubmittedOrder =
                    Locator.GetService<IOrderManager>().GetOrderWithStatus(
                        Locator.GetService<IContextObjects>().Get<CustomerHolder>().Object, OrderStatus.Draft);
            List<OrderItem> orderItems = preorder ? SubmittedOrder.Items.Where(i => i.Product.Qty < 1).ToList() : SubmittedOrder.Items.Where(i => i.Product.Qty > 0).ToList();
            if (orderItems.Count > 1)
            {
                gridProduct.DataSource = orderItems;
                gridProduct.DataBind();
                OrderCalculator calculator = new OrderCalculator(SubmittedOrder, preorder);
                var total = calculator.Total();
                ltItog.Text = total.ToString("C");
            }
            else
            {
                phMain.Visible = false;
                phNoItems.Visible = true;
            }
        }

        protected void gridProduct_DataBound(object sender, RepeaterItemEventArgs e)
        {
            OrderItem item = (OrderItem)e.Item.DataItem;
            HtmlGenericControl btnChangeSize = (HtmlGenericControl)e.Item.FindControl("btnChangeSize");
            if (btnChangeSize != null)
            {
                btnChangeSize.Visible = item.Product.Group.Products.Count > 1;
                btnChangeSize.Attributes["OnClick"] = "CreateOrOpenPopup('divOrderItem_" + item.Id + "', '', 400, '" +
                                                      item.Product.Group.Name + "', '', '', '','ChangeSize', 'id=" +
                                                      item.Id + "')";
            }
        }
    }
}
